<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="24" v-if="mode == 'edit'">
        <el-upload
          v-show="showFileList.length < max"
          class="upload-demo"
          :http-request="uploadQiniuCloud"
          ref="creativeUpload"
          :file-list="fileData"
          :on-change="beforeUpload"
          :show-file-list="false"
          :accept="getAccept()"
          list-type="picture-card"
          drag
          action="#"
          :auto-upload="true"
          multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">最多可以上传{{ max }}个文件，单个文件不可超过100M。</div>
        </el-upload>
      </el-col>

      <el-col :span="24" v-show="showFileList.length > 0">
        <ul class="el-upload-list el-upload-list--picture-card">
          <li v-for="(item,index) in showFileList" :key="index" class="el-upload-list__item is-ready">
            <span v-if="fileType(item) == 'image' || fileType(item) == 'video'">

              <span v-if="tickSeq > 0 && item.uid != null && fileMap[item.uid].url === '-1'">上传失败</span>
              <img
                v-if="tickSeq > 0 && (item.uid == null || fileMap[item.uid].progress == 100) && fileType(item) === 'image'"
                class="el-upload-list__item-thumbnail creative" :src="item.url"
                alt="">
              <video
                v-if="tickSeq > 0 && (item.uid == null || fileMap[item.uid].progress == 100) && fileType(item)  === 'video'"
                class="el-upload-list__item-thumbnail creative"
                :src="item.url"></video>
              <span class="el-upload-list__item-actions" @click="handlePictureCardPreview(item,$event)"
                    showdetail="true">
                <span class="el-upload-list__item-preview"><i class="el-icon-zoom-in"
                                                              @click="handlePictureCardPreview(item,$event)"
                                                              showdetail="true"></i></span>
                <span class="el-upload-list__item-preview" @click="handleQiniuDownload(item)"><i
                  class="el-icon-download"></i></span>
                <span class="el-upload-list__item-delete" @click="handleRemove(item)" v-if="mode == 'edit'"><i
                  class="el-icon-delete"></i></span>
              </span>
              <el-progress v-if="tickSeq > 0 && item.uid != null && fileMap[item.uid].progress != 100" type="circle"
                           :percentage="fileMap[item.uid].progress"></el-progress>
            </span>
            <span v-else>
                <el-progress v-if="tickSeq > 0 && item.uid != null && fileMap[item.uid].progress != 100" type="circle"
                             :percentage="fileMap[item.uid].progress"></el-progress>
                <span v-if="tickSeq > 0 && item.uid != null && fileMap[item.uid].url === '-1'">上传失败</span>
                <span v-if="tickSeq > 0 && (item.uid == null || fileMap[item.uid].progress == 100)">
                  <img style="height:120px;width:140px;margin-top:23px;" v-if="fileType(item) === 'excel'"
                       src="/img/icon/excel.png" alt="">
                  <img style="height:150px;width:150px;padding-top:8px" v-if="fileType(item) === 'zip'"
                       src="/img/icon/zip.png" alt="">
                  <div style="position: absolute; top: 0px; color: blue;">{{ item.name }}</div>
                </span>
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handleQiniuDownload(item)"><i
                    class="el-icon-download"></i></span>
                  <span class="el-upload-list__item-delete" @click="handleRemove(item)" v-if="mode == 'edit'"><i
                    class="el-icon-delete"></i></span>
                   <span class="el-upload-list__item-delete" @click="view(item)" v-if="mode == 'readonly'"><i
                     class="el-icon-view"></i></span>
                </span>
            </span>
          </li>
        </ul>
      </el-col>
    </el-row>

    <el-dialog
      :visible.sync="visble"
      width="50%"
      :close-on-click-modal="false"
      append-to-body>
      <iframe :src="visbleURL" frameborder="0" width="100%" height="600"></iframe>
    </el-dialog>

    <!-- 素材详情-->
    <el-dialog :visible.sync="dialogVisible" append-to-body top="0px;"
               :modal-append-to-body="false"
               :close-on-click-modal="true"
               :append-to-body="true"
               :show-close="false"
               :before-close="handleClose" width="60%" class="creative-detail-list">
      <div style="text-align: center;width: 100%;height: 100%">
        <div slot="title" style="text-align: right">
          <el-button class="dialog-close" size="mini" icon="el-icon-close" @click="handleClose"
                     circle></el-button>
        </div>
        <img :src="dialogImageUrl" v-if="dialogType === 'image'"/>
        <video v-if="dialogType === 'video'"
               ref="video" :src="dialogImageUrl" autoplay="autoplay" controls="controls"
               class="creative_edit"></video>
      </div>
    </el-dialog>
    <div id="downloadContent" style="display: none;"></div>
  </div>
</template>

<script>
import ObsClient from "esdk-obs-browserjs";
import FileSaver from "file-saver"
import * as qiniuTools from "../../util/qinnu_upload"

var obsClient;
export default {
  name: "creative_upload",
  data() {
    return {
      visble:false,
      visbleURL:'',
      fileMap: {},
      tickSeq: 1,
      accept: [
        {
          type: 'image',
          ext: ['jpg', 'jpeg', 'png', 'gif', 'bmp'],
        },
        {
          type: 'video',
          ext: ['mp4', 'mov', 'avi', 'mp3', 'ogg', 'rmvb', 'mkv'],
        },
        {
          type: 'zip',
          ext: ['jar', 'zip', 'rar', '7z', 'cab'],
        },
        {
          type: 'excel',
          ext: ['xlsx', 'xls'],
        },
      ],
      fileData: [],
      showFileList: [],
      dialogVisible: false,
      dialogType: '',
      dialogImageUrl: '',
    }
  },
  props: {
    data: Object,
    initFileList: Array,
    fileListChange: Function,
    uploadLen: Function,
    mode: String,
    max: {
      type: Number,
      default: 5,
    }
  },
  mounted() {
    if (this.initFileList.length > 0)
      this.showFileList = this.showFileList.concat(this.initFileList);
  },
  watch: {
    initFileList: {
      handler(val, old) {

        this.showFileList = []
        this.showFileList = this.showFileList.concat(this.initFileList);
      }
    }
  },
  methods: {
    updateShowList(fileList) {
      this.showFileList = fileList
      this.$refs.creativeUpload.uploadFiles = fileList
    },
    view(item){
      let type=item.url.substring(item.url.lastIndexOf('.')+1,item.url.length)
      // console.log(type)
      if (type!=='xlsx' && type!=='xls'){
        this.$message.warning('只支持Excel文件预览')
        return
      }
      this.visble=true
      this.visbleURL=`https://view.officeapps.live.com/op/view.aspx?src=${item.url}`
      // console.log(item)
    },
    getUploadFiles() {
      let uploadFiles = [];
      if (this.$refs.creativeUpload.uploadFiles != null) {
        this.$refs.creativeUpload.uploadFiles.forEach(file => {
          let fileInfo = this.fileMap[file.uid];
          if (fileInfo != null && fileInfo.url != null && fileInfo.url != '-1') {
            uploadFiles.push({
              name: file.name,
              url: fileInfo.url,
            });
          }
        });
      }
      return uploadFiles;
    },

    uploadQiniuCloud(file) {
      let self = this
      let fileData = qiniuTools.getFileData(file)
      let callback = {
        next(res) {
          // let fileIdx = self.fileMap.findIndex(item => item.uid === file.file.uid);
          // if(fileIdx !== -1) {
          // self.$set(self.fileMap[file.file.uid],'progress',Math.trunc(res.total.percent))

          if (self.fileMap[file.file.uid] !== undefined) {
            self.tickSeq++;
            self.fileMap[file.file.uid].progress = Math.trunc(res.total.percent)
          }

          // }
        },
        error(err) {
          this.$message({
            type: 'error',
            message: '图片上传失败！' + JSON.stringify(err)
          })
          let fileIdx = self.fileMap.findIndex(item => item.uid === file.file.uid);
          if (fileIdx !== -1) self.fileMap[fileIdx].url =
            '-1'
        },
        complete(res) {
          // let fileIdx = self.fileMap.findIndex(item => item.uid === file.file.uid);
          // if(fileIdx !== -1) {
          if (self.fileMap[file.file.uid] !== undefined) {
            self.fileMap[file.file.uid].url = 'http://' + fileData.server + '/' + res.key
            if (self.fileListChange) {
              self.fileListChange(this.data, self.fileMap[file.file.uid].url, 'add');
            }
          }
          // }
        }
      }
      let uploader = qiniuTools.uploadQiniuCloud(file, fileData)
      uploader.subscribe(callback)
    },

    //上传华为云
    uploadClient(file) {
      let self = this
      let fileType = this.fileType(file.file);
      let fileData = {
        server: 'obs.cn-east-3.myhuaweicloud.com',
        bucket: fileType === 'image' ? 'ads4each-image-full-size'
          : (fileType != null && fileType != '') ? 'ads4each-video-full-size' : '',
        name: Math.floor((Math.random() + Math.floor(Math.random() * 9 + 1)) * 10 ** (13 - 1)) + '',
        localName: file.file.name,
      }
      obsClient = new ObsClient({
        access_key_id: 'BVIEDCKS1F8VMR1FIOO8',
        secret_access_key: 'k3IQibnpbaqISScliV435aiwYjrDwaJwAh2p574s',
        server: fileData.server
      });

      //获取上传进度
      let callback = (transferredAmount, totalAmount) => {
        if (this.fileMap[file.file.uid]) {
          this.fileMap[file.file.uid].progress =
            Math.trunc(transferredAmount * 100.0 / totalAmount);
        }
        this.tickSeq++;
      };

      obsClient.putObject({
        Bucket: fileData.bucket,//判断是图片还是视频
        Key: fileData.name + "." + fileData.localName.split('.')[fileData.localName.split('.').length - 1].split('?')[0],
        SourceFile: file.file,
        ProgressCallback: callback
      }, (err, result) => {
        if (err) {
          this.$message({
            type: 'error',
            message: '图片上传失败！'
          })
          if (this.fileMap[file.file.uid]) {
            self.fileMap[file.file.uid].url = '-1'
          }
        } else {
          let self = this
          if (this.fileMap[file.file.uid]) {
            self.fileMap[file.file.uid].url =
              'https://' + fileData.bucket + '.' + fileData.server + '/' + fileData.name + '.' +
              fileData.localName.split('.')[fileData.localName.split('.').length - 1].split('?')[0]
          }
        }
        this.tickSeq++;
      });
    },
    uploadCompleted() {
      let uploadingCount = 0;
      this.showFileList.forEach(file => {
        if ((file.uid) && this.fileMap[file.uid]) {
          if (this.fileMap[file.uid].progress != 100) {
            uploadingCount++;
          } else {
            let lowerCaseUrl = this.fileMap[file.uid].url.toLowerCase();
            if (lowerCaseUrl == '-1' || lowerCaseUrl.startsWith('blob')) {
              uploadingCount++;
            }
          }
        }
      });
      return (uploadingCount == 0);
    },
    updateShowFileList() {
      if (this.mode === 'edit' && this.$refs.creativeUpload) {
        this.showFileList = this.$refs.creativeUpload.uploadFiles
      }
    },
    /**
     * 上传前
     */
    beforeUpload(file, fileList) {
      let acceptType = this.fileType(file);
      if (acceptType == null || acceptType == '') {
        this.postMessage("文件类型不支持!", "warning");
        this.remove(file);
        return;
      }
      if (this.showFileList.length >= this.max) {
        this.postMessage("文件个数已经达到" + this.max + "个!", "warning");
        this.remove(file);
        return;
      }
      if (file.size > 100 * 1024 * 1024) {
        this.postMessage("上传的单个文件不能超过100M!", "warning");
        this.remove(file)
        return false;
      }
      this.fileMap[file.uid] = {
        uid: file.uid,
        name: file.name,
        url: file.url,
        type: acceptType,
        progress: 0,
      };
      this.updateShowFileList();
      this.tickSeq++;
    },
    postMessage(msg, type) {
      let self = this;
      if (self.postSingleMessageDisable) {
        return;
      }
      self.postSingleMessageDisable = true;
      self.$message({
        message: msg,
        type: type,
        onClose: () => {
          self.postSingleMessageDisable = false;
        }
      });
    },
    /**
     * 素材详情
     */
    handlePictureCardPreview(file, event) {
      if (event == null || event.target.getAttribute('showdetail') != 'true') {
        return;
      }
      if (this.fileType(file) === 'image') {
        this.dialogType = 'image'
      } else if (this.fileType(file) === 'video') {
        this.dialogType = 'video'
      }
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleQiniuDownload(file) {
      // window.open(file.url)
      // console.log(file)
      const that = this
      var xhr = new XMLHttpRequest()
      let urlTail = ((file.url != null && file.url.indexOf('.') >= 0) ? (file.url.substring(file.url.lastIndexOf('.') + 1)) : '').toLowerCase();

      let options = {}
      if (urlTail == 'mp4' || urlTail == 'mov') {
        options = {type: 'video/' + urlTail}
      } else if (urlTail != '') {
        options = {type: 'image/' + urlTail}
      } else {
        return
      }
      xhr.open('GET', file.url, true)
      xhr.responseType = 'arraybuffer'
      xhr.onload = function () {
        debugger
        if (xhr.readyState === 4 && xhr.status === 200) {
          that.btnTitle = '下载'
          that.isLoading = false
          const blob = this.response
          // 转换一个blob链接
          const u = window.URL.createObjectURL(new Blob([blob], options))
          const a = document.createElement('a')
          a.download = file.name + '.' + urlTail
          a.href = u
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          a.remove()
        }
      }
      xhr.send()
    },
    handleDownload(file) {
      console.log(file)
      if (file.raw) {
        let content = document.getElementById("downloadContent");
        let aLink = document.createElement("a");
        content.appendChild(aLink);
        aLink.href = file.url;
        aLink.target = '_blank';
        aLink.download = file.name;
        aLink.click();
        aLink.remove();
      } else {
        const promise = this.downloadUrl(file.url).then(res => {
          var blob = new Blob([res])
          FileSaver.saveAs(blob, file.name);
        })
      }
    },
    downloadUrl(url) {
      return new Promise((resolve, reject) => {
        if (!url.startsWith('http')) {
          return;
        }
        let startDiv = (url.startsWith('https')) ? (url.indexOf('https://') + 'https://'.length) : (url.indexOf('http://') + 'http://'.length);
        let endDiv = url.indexOf('.', startDiv);
        let bucket = url.substring(startDiv, endDiv);
        startDiv = endDiv + 1;
        endDiv = url.indexOf('/', startDiv);
        let server = url.substring(startDiv, endDiv);
        endDiv = url.indexOf('?', startDiv);
        if (endDiv == -1) {
          endDiv = url.indexOf('&', startDiv);
        }
        if (endDiv == -1) {
          endDiv = url.length;
        }
        startDiv = url.lastIndexOf('/', endDiv) + 1;
        let targetName = url.substring(startDiv, endDiv);
        console.log(server)
        let obsClient = new ObsClient({
          access_key_id: 'BVIEDCKS1F8VMR1FIOO8',
          secret_access_key: 'k3IQibnpbaqISScliV435aiwYjrDwaJwAh2p574s',
          server: server,
        });
        obsClient.getObject({
          Bucket: bucket,
          Key: decodeURIComponent(targetName),
          SaveByType: 'arraybuffer'
        }, (err, result) => {
          if (err) {
            console.log('报错')
            reject(err)
          } else {
            resolve(result.InterfaceResult.Content)
          }
        });
      })
    },
    findFileIndex(file, fileList) {
      let index = fileList.findIndex((fileItem) => {
        return fileItem.uid === file.uid;
      });
      return index;
    },
    /**
     * 素材删除
     */
    handleRemove(file, fileList) {
      console.log('del', file, fileList)
      if (fileList != null) {
        let index = fileList.findIndex((fileItem) => {
          if ((file.uid) && (fileItem.uid)) {
            return fileItem.uid === file.uid;
          }
          if (!(file.uid) && !(fileItem.uid)) {
            return fileItem.url === file.url;
          }
          return false;
        });
        if (index == -1) {
          return;
        }
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          fileList.splice(index, 1);
          this.tickSeq++;
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          if (this.fileListChange) {
            this.fileListChange(this.data, file, 'delete');
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
          return
        });
      } else {
        this.handleRemove(file, this.showFileList);
        if (this.uploadLen) {
          this.uploadLen(this.showFileList.length, this.creative)
        }
      }
    },
    remove(file, fileList) {
      if (fileList != null) {
        let index = fileList.findIndex((fileItem) => {
          if ((file.uid) && (fileItem.uid)) {
            return fileItem.uid === file.uid;
          }
          if (!(file.uid) && !(fileItem.uid)) {
            return fileItem.url === file.url;
          }
          return false;
        });
        if (index == -1) {
          return;
        }
        fileList.splice(index, 1);
      } else {
        if (file.uid) this.remove(file, this.$refs.creativeUpload.uploadFiles);
        if (this.fileListChange) {
          this.fileListChange(this.data, file, 'delete');
        }
        if (this.uploadLen) {
          this.uploadLen(this.$refs.creativeUpload.uploadFiles.length, this.creative)
        }
      }
    },
    /**
     * 文件类型
     * @param file
     * @returns {string}
     */
    getAccept() {
      let list = [];
      this.accept.forEach((accept) => {
        accept.ext.forEach((ext) => {
          list.push('.' + ext);
        })
      })
      return list.join(', ');
    },
    fileType(file) {
      let url = file.url;
      if (url != null) {
        url = url.split('?')[0];
      }
      let name = file.name;
      if (name != null) {
        name = name.split('?')[0];
      }

      let urlTail = ((url != null && url.indexOf('.') >= 0) ? (url.substring(url.lastIndexOf('.') + 1)) : '').toLowerCase();
      let nameTail = ((name != null && name.indexOf('.') >= 0) ? (name.substring(name.lastIndexOf('.') + 1)) : '').toLowerCase();

      for (let n = 0; n < this.accept.length; n++) {
        let accept = this.accept[n];
        if (accept.ext.includes(urlTail) || accept.ext.includes(nameTail)) {
          return accept.type;
        }
      }
      return null
    },
    /**
     * 关闭素材详情弹窗
     */
    handleClose() {
      if (this.dialogVisible) {
        if (this.dialogType === 'video') {
          this.$refs.video.pause();
        }
        this.dialogVisible = false;
      }
    }
  }
}
</script>

<style scoped lang="scss">
// /deep/ .is-ready{
//   // margin-left: 100px;
//   width: 500px;
//   height: 300px;
//   // width: 50%;
//   // height: 40%;
// }
.upload-demo {
  /deep/ .el-upload--picture-card {
    width: 360px;
    height: 180px;
  }

  /deep/ .el-upload--picture-card {
    line-height: 0;
  }
}

.creative_list {
  /deep/ .el-upload-list__item {
    text-align: center;
    vertical-align: middle;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  /deep/ .el-upload-list--picture-card {
    display: flex;
    flex-wrap: wrap;
  }

  .creative {
    max-height: 100%;
    max-width: 100%;
    height: auto;
    width: auto;
    vertical-align: middle
  }

}

.file_style {
  margin-top: 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  line-height: 21px;
  width: 100%;
  padding: 0 20px;
  cursor: pointer;

  div:nth-of-type(1) {
    width: 21px;
    height: 21px;
    padding-right: 26px;
    align-self: center;

    img {
      width: 100%;
      height: 100%;
    }
  }

  div:nth-of-type(2) {
    flex: 1;
  }

  div:nth-of-type(3) {
    width: 21px;
    font-size: 16px;
    text-align: center;
    color: #409eff;
    cursor: pointer;
  }
}

.file_style:hover {
  transition: all .5s cubic-bezier(.55, 0, .1, 1);
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
  margin-top: 5px;
  position: relative;
  box-sizing: border-box;
  border-radius: 4px;
  width: 100%;
  background: silver;

  div:nth-of-type(3) {
    color: white;
  }
}

.creative-detail-list {
  .dialog-close {
    margin-bottom: 20px;
    background-color: rgba(255, 255, 255, 0);
    color: white;
  }

  /deep/ .el-dialog {
    background: rgba(255, 255, 255, 0);
    -webkit-box-shadow: none;
    box-shadow: none;
  }

  /deep/ .el-dialog__header {
    padding: 0;
  }

  img {
    width: auto;
    height: auto;
    max-width: 80%;
    max-height: 80vh;
  }

  /deep/ video {
    width: auto;
    height: auto;
    max-width: 80%;
    max-height: 80vh;
  }
}
</style>
